package hzq.mybatis.source.demo1.dao.impl;

import hzq.mybatis.source.demo1.dao.IUserDao;
import hzq.mybatis.source.demo1.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * Created by hzq on 2017/3/27.
 */
public class UserDaoImpl implements IUserDao {
    @Override
    public void insert(User user) {
        SqlSession session = this.getSqlSessionFactory().openSession();
        session.insert("UserMapper.insert",user);
        session.commit();
        session.close();

    }

    @Override
    public List<User> list() {
        SqlSession session  = this.getSqlSessionFactory().openSession();
        List<User> users = session.selectList("UserMapper.list");
        session.close();
        return users;
    }

    @Override
    public void update(User user) {
        SqlSession session = this.getSqlSessionFactory().openSession();
        session.update("UserMapper.update",user);
        session.commit();
        session.close();
    }

    /**
     * 获取 SqlSessionFactory
     * Mybatis 通过SqlSessionFactory获取SqlSession, 然后才能通过SqlSession与数据库进行交互
     * @return
     */
    private SqlSessionFactory getSqlSessionFactory(){
        String resource = "mybatis-config.xml";
        SqlSessionFactory sqlSessionFactory = null;
        InputStream stream =  null;
        try {
            stream = Resources.getResourceAsStream(resource);
            Properties prop = new Properties();
            prop.setProperty("username","root");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream,prop);
        }catch (Exception e){
            e.printStackTrace();
        }
        return  sqlSessionFactory;
    }
}
